package 数据结构.search;

import java.util.Arrays;

/**
 * 斐波那契数列算法
 */
public class FibonacciSearch {
    public static int maxSize = 20;

    public static void main(String[] args) {

        int[] arr = {1, 8, 10, 89, 1000, 1234};
        int i = fibSearch(arr, 10);
        System.out.println(i);
    }

    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < maxSize; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }

    //斐波那契查找算法

    /**
     * @param a   数组
     * @param kye 查找的值
     * @return
     */
    public static int fibSearch(int[] a, int kye) {
        int low = 0;
        int high = a.length - 1;
        int k = 0;//表示斐波那契数 的下标
        int mid = 0;//存放mid
        int[] f = fib();

        //获取到key
        while (high > f[k] - 1) {
            k++;
        }

        int[] temp = Arrays.copyOf(a, f[k]);
        for (int i = high + 1; i < temp.length; i++) {
            temp[i] = a[high];
        }
        //判断
        while (low <= high) {
            mid = low + f[k - 1] - 1;
            if (kye < temp[mid]) {//向左查找
                high = mid - 1;
                k--;
            } else if (kye > temp[mid]) {
                low = mid + 1;
                k -= 2;
            } else {
                if (mid > high) {
                    return high;//一直向右查找的结果
                } else {
                    return mid;
                }
            }
        }
        return -1;

    }
}
